import React, { useContext, useEffect, useMemo, useRef } from "react";
import { global_theme, ITheme } from "../Theme";
import { IConfig } from "./IConfig";

export const global_context = React.createContext<IConfig>({ theme: global_theme })
export interface IConfigProviderProps extends React.PropsWithChildren {
  ctx?: React.Context<IConfig>
  theme?: ITheme;
}

export function ConfigProvider(props: IConfigProviderProps) {
  const {
    ctx: { Provider } = global_context,
    theme = global_theme
  } = props;

  const value = useMemo<IConfig>(() => ({
    theme,
  }), [theme])

  const ref_style_ele_id = useRef<string>();
  useEffect(() => {

    const ele_style = document.createElement('style')
    ele_style.id = ref_style_ele_id.current = 'gimd_auto_gen_style_' + Date.now();

    Promise.all([
      import('../Text/styling').then((mod) => {
        ele_style.innerHTML += mod.default(theme)
      })
    ]).finally(() => {
      if (ref_style_ele_id.current === ele_style.id)
        document.head.appendChild(ele_style);
    })
    return () => {
      const ele_id = ref_style_ele_id.current;
      if (!ele_id) return;
      document.getElementById(ele_id)?.remove()
    }
  }, [theme])

  return (
    <Provider value={value}>
      {props.children}
    </Provider>
  )
}

export function useConfig(ctx = global_context) {
  return useContext(ctx);
}

ConfigProvider.useConfig = useConfig;
ConfigProvider.context = global_context;